package com.controller;

import com.annotations.RequestMappping;
import com.pojo.*;
import com.service.AddressService;
import com.service.CartService;
import com.service.OderService;
import com.service.impl.AddressServiceImpl;
import com.service.impl.CartServiceImpl;
import com.service.impl.OderServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RequestMappping("/order")
public class OrderController {

    private CartService cartService = new CartServiceImpl();
    private AddressService addressService = new AddressServiceImpl();
    private OderService oderService = new OderServiceImpl();

    @RequestMappping("/preView")
    public String preView(HttpServletRequest request, HttpServletResponse response) {
        TbUser loginUser = (TbUser) request.getSession().getAttribute("loginUser");
        Long uid = loginUser.getId();
        if (request.getSession().getAttribute("cart") == null) {
            List<CartItem> cartItemList = cartService.findCartByUid(uid);//获取到购物车数据
            request.getSession().setAttribute("cart", cartItemList);
        }

        if (request.getSession().getAttribute("addressList") == null) {
            //获取购物车数据
            //获取地址数据
            List<TbAddress> addressList = addressService.findAllAddresByUid(uid);
            //携带数据
            //跳转到预览页面
            request.getSession().setAttribute("addressList", addressList);
        }

        return "forward:/order.jsp";

    }

    @RequestMappping(("/create"))
    public String createOrder(HttpServletRequest request, HttpServletResponse response) {
        //创建订单需要知道购买的商品和数量,我们直接把购物车里面所有的数据都下单
        List<CartItem> cart = (List<CartItem>) request.getSession().getAttribute("cart");//先获取到要下单的商品
        //还得知道地址选择的是哪个, 地址从前端传过来
        String aid = request.getParameter("aid");//用户选择的地址
        Order order = oderService.createOrder(cart, aid);
        request.getSession().setAttribute("order",order);
        //携带数据 数据在哪?
        return "redirect:/orderSuccess.jsp";
    }

    @RequestMappping("/show")
    public String show(HttpServletRequest request, HttpServletResponse response) {
        TbUser loginUser = (TbUser) request.getSession().getAttribute("loginUser");
        Long uid = loginUser.getId();
        List<TbOrder>allOderdata=null;
        try {
            allOderdata = oderService.findAllOrder(uid);
            request.getSession().setAttribute("orderList", allOderdata);
             return "redirect:/orderList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/error/error.jsp";
    }
   @RequestMappping("/cancel")
    public String cancel(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        oderService.cancelOrder(id);
       show(request, response);
        request.getSession().removeAttribute("orderList");
        return "redirect:/orderList";
    }
}


